'use strict';
import React,{Component} from 'react';
import Util from '../../common/util';
import * as URLconstant from '../../constant/URLconstant'
import Header from '../../common/header';
import Swiper from 'react-native-swiper';
import Modal from 'react-native-modalbox';
import ConfirmOrder from '../../order/confirmOrder';//提交订单
import {
    View,
    Text,
    ScrollView,
    StyleSheet,
    Image,
    TouchableOpacity
} from 'react-native';
import MyStroage from "../../common/myStroage";
import Toast from '../../common/ToastUtil';
export default class seckillIndex extends Component{
    // 构造
      constructor(props) {
        super(props);
        // 初始状态
        this.state = {
            user_id:'',
            goodsData:null,
            curTime:0,
            buy_num:1,
            imgHeightList:[],
            isOpen:false,
            spec_1:'',
            spec_2_list:[],
            spec_id:''
        };
        this.getIndexSuc=this.getIndexSuc.bind(this)
          this.errorCallback=this.errorCallback.bind(this)
      }

    componentDidMount() {
        this.getUser()
    }

     async getUser(){
        try{
            let userInfoDate = await MyStroage.getStorageAllDataForKey('userinfo')
            LOG('userInfoDate==='+JSON.stringify(userInfoDate))
            if(userInfoDate){
                this.setState({
                    user_id:userInfoDate.data.user_id
                })
                this.getSeckillIndex()
            }else{
                Toast.show('请先登录')
            }
        }catch (e){

        }
    }

    componentWillUnMount() {
        this.getTimer&&clearInterval(this.getTimer)
    }

      getSeckillIndex(){
        let url = URLconstant.GET_SECKILL_INDEX
          let datakey=[]
          datakey['user_id']=this.state.user_id
          datakey['spree_id']=this.props.spree_id
          Util.get(url,datakey,this.getIndexSuc,this.errorCallback)
      }
    getIndexSuc(datas){
        if(datas.status==0){
            let goodsData=datas.data
            let spec_1 = ''
            if(goodsData.size.length!=0){
                spec_1=goodsData.size[0]
            }
            this.setState({
                goodsData:datas.data,
                spec_price:datas.data.spree.price,
                spec_1:spec_1
            })
            if(spec_1!=''){
                this.getSpec2List(spec_1)
            }
            if(datas.data.goods_detail.length>0){
                this.getImgHeight(datas.data.goods_detail)
            }
            this.getCurrentTime()
        }else{
            Toast.show(datas.msg)
            this.props.navigator.pop()
        }
    }

    getCurrentTime(){
        let that = this
        this.getTimer = setInterval(function () {
            let timestamp = parseInt((new Date()).getTime() / 1000)
            that.setState({
                curTime:timestamp,
            })
        },1000)
    }



    errorCallback(err){

    }

    async getImgHeight(urls) {
        try {
            let list = [];
            await urls.map((url, index) => {
                LOG("url==="+url)
                Image.getSize(url, (width, height) => {
                    let imgheight = Util.size.width * height / width;
                    list[index]=imgheight
                    if(list.length==urls.length){
                        LOG('list==='+list)
                        this.setState({
                            imgHeightList:list,
                        })
                    }
                }, (error) => {
                    LOG('图片路径错误。。。。。。。。' + error);
                })
            })
        } catch (err) {
            LOG(err);
        }
    }

    //轮播图
    showGoodsSwiper(){
        let goodsData = this.state.goodsData
        let img_list = goodsData.img_list
        if(img_list.length==0){
              return false
        } else if(img_list.length==1){
            return(
                <View style={styles.swiper_view}>
                    <Image
                        source={{uri:img_list[0].image_url}}
                        resizeMode={'cover'}
                        style={{width:Util.size.width,height:Util.size.width}}
                    />
                </View>
            )
        }else{
              return(
                  <Swiper
                      showsButtons={false}
                      autoplay={true}
                      height={Util.size.width}
                      paginationStyle={{bottom:3,}}
                      autoplayTimeout={5}
                      activeDot={<View style={{backgroundColor: '#f00', width: 12, height: 12, borderRadius: 6, marginLeft: 5, marginRight: 5, marginTop: 5, marginBottom: 5,}} />}
                  >
                      {
                          img_list.map((item,index)=>{
                              return(
                                  <Image
                                      key={index}
                                      source={{uri:item.image_url}}
                                      resizeMode={'cover'}
                                      style={{width:Util.size.width,height:Util.size.width}}
                                  />
                              )
                          })
                      }
                  </Swiper>
              )
        }
    }

    //状态和价格
    statusShow(){
          let goodsData = this.state.goodsData
            let is_start = goodsData.spree.is_start
        let is_end = goodsData.spree.is_end
        let status
        if(is_start==1&&is_end==0){
            status=1 //活动中
        }else if(is_start==0){
            status=0 //未开始
        }else {
            status=2//已经结束
        }
        return(
            <View style={styles.status_show}>
                <View style={status==2?styles.status_left2:styles.status_left}>
                    <Text style={styles.seckill_price}>¥{goodsData.spree.price}</Text>
                    <View style={styles.old_price_view}>
                        <Text style={{fontSize:12,color:"#fff"}}>原价：</Text>
                        <Text style={{fontSize:12,color:"#fff",textDecorationLine:"line-through"}}>¥{goodsData.spree.market_price}</Text>
                    </View>
                </View>
                {
                    status==2?
                        null:
                        <View style={styles.status_right}>
                            {
                                status==0?
                                    <Text style={{fontSize:12,color:"#F23257"}}>距开始还剩：</Text>
                                    :
                                    <Text style={{fontSize:12,color:"#F23257"}}>距结束还剩：</Text>
                            }
                            {this.showTime(status)}
                        </View>
                }
            </View>
        )
    }

    showTime(status){
        let goodsData = this.state.goodsData
        let time
        if(status==0){
            time=goodsData.spree.start_time
        }else{
            time=goodsData.spree.end_time
        }
        let curTime = this.state.curTime
        if(curTime==0){
            curTime=parseInt((new Date()).getTime() / 1000)
        }
        let lastTime

        if(curTime>time){
            lastTime=curTime-time
        }else{
            lastTime=time-curTime
        }

        let second = 0
        let minute = 0
        let hour = 0
        let day = 0
        if (lastTime > 60) {
            second = parseInt(lastTime % 60)
            minute = parseInt(lastTime / 60)
            if (minute > 60) {
                hour = parseInt(minute / 60)
                minute = parseInt(minute % 60)
                if (hour > 24) {
                    day = parseInt(hour / 24) //日
                    hour = parseInt(hour % 24) //时
                }
            }
        } else {
            second = time
        }
        hour = hour > 0 ? (hour < 10 ? "0" + hour : hour) : '00'
        minute = minute > 0 ? (minute < 10 ? "0" + minute : minute) : '00'
        second = second > 0 ? (second < 10 ? "0" + second : second) : '00'
        return(
            <View style={[styles.time_view,{marginTop:5}]}>
                {
                    day>0?
                        <View style={styles.time_view}>
                            <View style={styles.time_item}>
                                <Text style={{fontSize:12,color:"#fff"}}>{day}天</Text>
                            </View>
                            <Text style={styles.time_mao}>:</Text>
                        </View>
                        :
                        null
                }
                <View style={styles.time_view}>
                    <View style={styles.time_item}>
                        <Text style={{fontSize:12,color:"#fff"}}>{hour}</Text>
                    </View>
                    <Text style={styles.time_mao}>:</Text>
                </View>
                <View style={styles.time_view}>
                    <View style={styles.time_item}>
                        <Text style={{fontSize:12,color:"#fff"}}>{minute}</Text>
                    </View>
                    <Text style={styles.time_mao}>:</Text>
                </View>
                <View style={styles.time_view}>
                    <View style={styles.time_item}>
                        <Text style={{fontSize:12,color:"#fff"}}>{second}</Text>
                    </View>
                </View>
            </View>
        )
    }

    addDelNum(type){
        let buy_num = this.state.buy_num
        let goodsData = this.state.goodsData
        let max_buynum = goodsData.spree.max_buynum
        if(type=='del'){
            if(buy_num>1){
                buy_num--
            }
        }else{
            if(buy_num<max_buynum){
                buy_num++
            }else{
                Toast.show('已达最大购买数')
            }
        }
        this.setState({
            buy_num:buy_num
        })
    }

    //商品信息
    showGoodsInfo(){
        let goodsData = this.state.goodsData
        return(
            <View style={{padding:10,backgroundColor:"#fff"}}>
                <Text style={{fontSize:14,color:"#333",lineHeight:25,}}>{goodsData.spree.spree_name}</Text>
                <View style={styles.buy_count_view}>
                    <Text style={{fontSize:12,color:"#999"}}>购买数量：</Text>
                    <View style={styles.del_add_view}>
                        <TouchableOpacity onPress={()=>this.addDelNum('del')} style={styles.del_view}>
                            <Text style={{fontSize:14,color:"#999"}}>-</Text>
                        </TouchableOpacity>
                        <View style={styles.btn_num_view}>
                            <Text style={{fontSize:14,color:"#999"}}>{this.state.buy_num}</Text>
                        </View>
                        <TouchableOpacity onPress={()=>this.addDelNum('add')} style={styles.del_view}>
                            <Text style={{fontSize:14,color:"#999"}}>+</Text>
                        </TouchableOpacity>
                    </View>
                </View>
                <View style={styles.sale_view}>
                    <View style={[styles.sale_item,styles.item_view_left]}>
                        <Text style={{fontSize:12,color:"#696969"}}>最多抢购数:{goodsData.spree.max_buynum}</Text>
                    </View>
                    <View style={[styles.sale_item,styles.item_view_center]}>
                        <Text style={{fontSize:12,color:"#696969"}}>库存:{goodsData.stock}</Text>
                    </View>
                    <View style={[styles.sale_item,styles.item_view_right]}>
                        <Text style={{fontSize:12,color:"#696969"}}>销量:{goodsData.sale}</Text>
                    </View>
                </View>
                {
                    goodsData.goods_lable?
                        <View style={[styles.sale_view,styles.border_b]}>
                            {
                                goodsData.goods_lable.map((item,index)=>{
                                    return(
                                        <View style={[styles.sale_item,index==0?styles.flex_start:(index==1?styles.flex_center:styles.flex_end)]} key={index}>
                                            <Image
                                                source={{uri:item.lable_image}}
                                                resizeMode={'cover'}
                                                style={{width:15,height:15,marginRight:5}}
                                            />
                                            <Text style={{fontSize:12,color:"#696969"}}>{item.lable_name}</Text>
                                        </View>
                                    )
                                })
                            }
                        </View>
                        :null
                }

            </View>
        )
    }

    showGoodsImage(){
        let goodsData = this.state.goodsData
        let imgHeightList = this.state.imgHeightList
        return(
            <View>
                <View style={styles.img_info_title}>
                    <Text style={{fontSize:12,color:"#999"}}>---上拉继续查看商品详情---</Text>
                </View>
                {
                    goodsData.goods_detail?
                        <View>
                            {
                                goodsData.goods_detail.map((item,index)=>{
                                    return(
                                        <Image
                                            source={{uri:item}}
                                            key={index}
                                            style={{width:Util.size.width,height:imgHeightList[index]}}
                                            resizeMode={'cover'}
                                        />
                                    )
                                })
                            }
                        </View>
                        :null
                }
            </View>
        )
    }

    showBuyBtn(){
        let goodsData = this.state.goodsData
        let is_start = goodsData.spree.is_start
        let is_end = goodsData.spree.is_end
        let status
        let txt = ''
        if(is_start==1&&is_end==0){
            status=1 //活动中
            txt='立即购买'
        }else if(is_start==0){
            status=0 //未开始
            txt='等待秒杀'
        }else {
            status=2//已经结束
            txt='活动结束'
        }
        if(status==1){
            return(
                <TouchableOpacity style={styles.buy_btn} onPress={()=>this.setState({isOpen:true})}>
                    <Text style={{fontSize:14,color:"#fff"}}>{txt}</Text>
                </TouchableOpacity>
            )
        }else{
            return(
                <View style={styles.buy_btn2}>
                    <Text style={{fontSize:14,color:"#fff"}}>{txt}</Text>
                </View>
            )
        }
    }

    async selectSpec1(spec){
          await this.setState({
              spec_1:spec,
              spec_2:"",
              spec_id:''
          })
        this.getSpec2List(spec)
    }

    getSpec2List(spec){
        let goodsData = this.state.goodsData
        let goods_spec = goodsData.goods_spec
        let spec_1_list = goods_spec[spec]
        let spec_2_list = [];
        let spec_2 = ''
        for (let item in spec_1_list) {
            if(item!=''){
                spec_2_list.push(item)
            }
        }
        if(spec_2_list.length>0) {
            spec_2 = spec_2_list[0]
        }
        this.getSpecID(spec_2)
        this.setState({
            spec_2_list: spec_2_list,
            spec_2:spec_2
        })
    }

    selectSpec2(spec){
          this.setState({
              spec_2:spec
          })
        this.getSpecID(spec)
    }

    getSpecID(spec2){
        let spec_2=spec2==undefined?"":spec2
        let goodsData = this.state.goodsData
        let goods_spec = goodsData.goods_spec
        let spec_1 = this.state.spec_1
        LOG('spec_1==='+spec_1)
        let spec_id = goods_spec[spec_1][spec_2].spec_id
        let spec_price = goods_spec[spec_1][spec_2].price
        this.setState({
            spec_id:spec_id,
            spec_price:spec_price
        })
    }

    showBuyModal(){
          let goodsData = this.state.goodsData
          return(
              <Modal
                  style={styles.buy_modal}
                  isOpen={this.state.isOpen}
                  position={"bottom"}
                  swipeToClose={false}
                  backdropPressToClose={false}
                  onClosed={()=>this.setState({isOpen:false})}
              >
                  <TouchableOpacity onPress={()=>this.setState({isOpen:false})} style={styles.close_btn_view}>
                      <Image
                          source={require('../../imgs/close.png')}
                          style={{width:20,height:20}}
                          resizeMode={'cover'}
                      />
                  </TouchableOpacity>
                <View style={styles.modal_top}>
                    <View style={{width:65,height:65}}>
                        <Image
                            source={{uri:goodsData.spree.picture}}
                            style={{width:65,height:65}}
                        />
                    </View>
                    <View style={styles.top_price_view}>
                        <Text style={{fontSize:14,color:"#333"}}>{goodsData.spree.spree_name}</Text>
                        <Text style={{fontSize:14,color:"#f02b4d"}}>¥{this.state.spec_price}</Text>
                    </View>
                </View>
                  <ScrollView style={styles.spec_select_wrap}>
                      {
                          goodsData.size.length==0?
                              null
                              :
                              <View style={[styles.border_top,{marginTop:10}]}>
                                  <View style={{paddingHorizontal:10,paddingBottom:5}}>
                                      <Text>{goodsData.spec_name_1}</Text>
                                  </View>
                                  <View style={styles.spec_select_item_wrap}>
                                      {
                                          goodsData.size.map((item,index)=>{
                                              return(
                                                  <TouchableOpacity onPress={()=>this.selectSpec1(item)} key={index} style={item==this.state.spec_1?styles.selectSpecItem:styles.specItem}>
                                                      <Text style={{fontSize:12,color:"#fff"}}>{item}</Text>
                                                  </TouchableOpacity>
                                              )
                                          })
                                      }
                                  </View>
                                  {
                                      this.state.spec_2_list.length==0?
                                          null:
                                        <View style={{marginTop:10}}>
                                            <View style={{paddingHorizontal:10,paddingBottom:5}}>
                                                <Text>{goodsData.spec_name_2}</Text>
                                            </View>
                                          <View style={styles.spec_select_item_wrap}>
                                              {
                                                  this.state.spec_2_list.map((item,index)=>{
                                                      return(
                                                          <TouchableOpacity onPress={()=>this.selectSpec2(item)} key={index} style={item==this.state.spec_2?styles.selectSpecItem:styles.specItem}>
                                                              <Text style={{fontSize:12,color:"#fff"}}>{item}</Text>
                                                          </TouchableOpacity>
                                                      )
                                                  })
                                              }
                                          </View>
                                        </View>
                                  }
                              </View>
                      }
                  </ScrollView>
                  <TouchableOpacity style={styles.buy_btn} onPress={()=>this.toBuy()}>
                      <Text style={{fontSize:14,color:"#fff"}}>立即购买</Text>
                  </TouchableOpacity>
              </Modal>
          )
    }
    toBuy(){
          let spec_id = this.state.spec_id
        let spree_id = this.props.spree_id
        let goods_id = this.props.goods_id
        let buy_num = this.state.buy_num
        let user_id = this.state.user_id
        let goodsData = this.state.goodsData
        if(goodsData.goods_spec.length!=0&&spec_id==''){
            Toast.show('请先选择规格')
            return false
        }
        this.props.navigator.push({
            component:ConfirmOrder,
            passProps:{
                spec_id:spec_id,
                spree_id:spree_id,
                goods_id:goods_id,
                buy_num:buy_num,
                isKill:true,
                user_id:user_id
            }
        })
    }


      render(){
          return(
              <View style={{flex:1,backgroundColor:"#f0f0f0"}}>
                  <Header navigator={this.props.navigator} initObj={{ title: '秒杀详情',id:2}}/>
                  {
                    this.state.goodsData==null?
                        <View style={{flex:1}}>
                            {Util.loading()}
                        </View>
                        :
                        <View style={{flex:1}}>
                            <ScrollView style={{flex:1}}>
                                {this.showGoodsSwiper()}
                                {this.statusShow()}
                                {this.showGoodsInfo()}
                                {this.showGoodsImage()}
                            </ScrollView>
                            {this.showBuyBtn()}
                            {this.showBuyModal()}
                        </View>
                  }
              </View>
          )
      }
}
var styles = StyleSheet.create({
    swiper_view:{
        width:Util.size.width,
        height:Util.size.width
    },
    status_show:{
        height:50,
        flexDirection:'row',
        justifyContent:'space-between'
    },
    status_left:{
        paddingLeft:10,
        backgroundColor:"#f02b4d",
        flex:1,
    },
    seckill_price:{
        fontSize:20,
        color:"#fff"
    },
    old_price_view:{
        flexDirection:"row",
        alignItems:'center',
    },
    status_right:{
        paddingHorizontal:15,
        backgroundColor:"#ffe7e6",
        alignItems:'center',
        justifyContent:'center'
    },
    time_view:{
        flexDirection:'row',
        alignItems:'center',
        justifyContent:'center'
    },
    time_item:{
        backgroundColor:"#F23257",
        paddingHorizontal:5,
        height:20,
        alignItems:'center',
        justifyContent:'center',
        borderRadius:5,

    },
    time_mao:{
        fontSize:12,
        color:"#F23257",
        marginHorizontal:2
    },
    buy_count_view:{
        flexDirection:"row",
        alignItems:'center',
        marginTop:10,
    },
    del_add_view:{
        marginLeft:10,
        flexDirection:'row',
        borderWidth:1,
        borderColor:"#ddd"
    },
    del_view:{
        width:25,
        height:25,
        backgroundColor:"#ecebeb",
        alignItems:'center',
        justifyContent:'center'
    },
    btn_num_view:{
        width:45,
        height:25,
        alignItems:'center',
        justifyContent:'center'
    },
    sale_view:{
        flexDirection:'row',
        alignItems:'center',
        marginTop:10,
        height:40,
        backgroundColor:"#fff",
    },
    sale_item:{
        flexDirection:'row',
        alignItems:'center',
        width:(Util.size.width-20)/3,
    },
    flex_start:{
        justifyContent:'flex-start'
    },
    flex_center:{
        justifyContent:'center'
    },
    flex_end:{
        justifyContent:'flex-end'
    },
    item_view_left:{
        justifyContent:'flex-start'
    },
    item_view_center:{
        justifyContent:'center'
    },
    item_view_right:{
        justifyContent:'flex-end'
    },
    border_b:{
        borderTopWidth:1,
        borderTopColor:"#e0e0e0"
    },
    img_info_title:{
        alignItems:'center',
        justifyContent:'center',
        padding:10,
    },
    buy_btn:{
        width:Util.size.width,
        height:40,
        alignItems:'center',
        justifyContent:'center',
        backgroundColor:"#f02b4d"
    },
    buy_btn2:{
        width:Util.size.width,
        height:40,
        alignItems:'center',
        justifyContent:'center',
        backgroundColor:"#c5c5c5"
    },
    buy_modal:{
        width:Util.size.width,
        height:Util.size.height/2,
        backgroundColor:"#fff"
    },
    close_btn_view:{
        position:'absolute',
        top:10,
        right:10
    },
    modal_top:{
        padding:10,
        flexDirection:'row'
    },
    top_price_view:{
        paddingHorizontal:10,
        paddingVertical:5,
        justifyContent:'space-between'
    },
    spec_select_wrap:{
        flex:1,
    },
    spec_select_item_wrap:{
        paddingHorizontal:10,
        flexDirection:'row',
        flexWrap:'wrap',
    },
    border_top:{
        borderTopWidth:1,
        borderTopColor:"#e0e0e0",
        paddingVertical:10
    },
    selectSpecItem:{
        alignItems:'center',
        justifyContent:'center',
        paddingHorizontal:10,
        height:25,
        borderRadius:5,
        marginHorizontal:10,
        marginVertical:5,
        backgroundColor:"#f02b4d"
    },
    specItem:{
        alignItems:'center',
        justifyContent:'center',
        paddingHorizontal:10,
        height:25,
        borderRadius:5,
        marginHorizontal:10,
        marginVertical:5,
        backgroundColor:"#ccc"
    }
})